<template>
  <div class="order-list-page">
    <HeaderNav />
    
    <div class="container" v-loading="loading">
      <!-- 面包屑 -->
      <el-breadcrumb separator="/" class="breadcrumb">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>我的订单</el-breadcrumb-item>
      </el-breadcrumb>

      <!-- 状态筛选 -->
      <div class="filter-tabs">
        <el-tabs v-model="activeStatus" @tab-change="handleStatusChange">
          <el-tab-pane label="全部" name=""></el-tab-pane>
          <el-tab-pane label="待发货" name="1"></el-tab-pane>
          <el-tab-pane label="配送中" name="2"></el-tab-pane>
          <el-tab-pane label="待取件" name="3"></el-tab-pane>
          <el-tab-pane label="已完成" name="4"></el-tab-pane>
          <el-tab-pane label="已取消" name="5"></el-tab-pane>
        </el-tabs>
      </div>

      <!-- 订单列表 -->
      <div class="order-list" v-if="orderList.length > 0">
        <div v-for="order in orderList" :key="order.id" class="order-card">
          <div class="order-header">
            <div class="order-info">
              <span class="order-no">订单号：{{ order.orderNo }}</span>
              <span class="order-time">{{ formatTime(order.createTime) }}</span>
            </div>
            <div class="order-status">
              <el-tag :type="getStatusTagType(order.orderStatus)">
                {{ getStatusText(order.orderStatus) }}
              </el-tag>
            </div>
          </div>

          <div class="order-items">
            <div
              v-for="item in order.orderItems"
              :key="item.productId"
              class="order-item"
            >
              <img
                :src="getImageUrl(item.productImage)"
                :alt="item.productName"
                class="item-image"
                @error="handleImageError"
              />
              <div class="item-info">
                <h4 class="item-name">{{ item.productName }}</h4>
                <div class="item-spec">
                  <span class="item-price">¥{{ formatPrice(item.unitPrice) }}</span>
                  <span class="item-quantity">x{{ item.quantity }}</span>
                </div>
              </div>
            </div>
          </div>

          <div class="order-footer">
            <div class="order-total">
              合计：<span class="total-price">¥{{ formatPrice(order.actualAmount) }}</span>
            </div>
            <div class="order-actions">
              <el-button
                v-if="order.paymentStatus === 0 && order.orderStatus !== 4 && order.orderStatus !== 5"
                type="primary"
                @click="handlePay(order.id)"
              >
                立即支付
              </el-button>
              <el-button
                v-if="order.paymentStatus === 1 && order.orderStatus !== 4 && order.orderStatus !== 5"
                type="info"
                plain
                @click="handleViewLogistics(order.id)"
              >
                查看物流
              </el-button>
              <el-button
                type="primary"
                plain
                @click="handleViewDetail(order.id)"
              >
                查看详情
              </el-button>
              <el-button
                v-if="order.orderStatus === 1 && order.paymentStatus === 0"
                type="danger"
                plain
                @click="handleCancel(order.id)"
              >
                取消订单
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <el-empty v-else description="暂无订单" />

      <!-- 分页 -->
      <div v-if="total > 0" class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import HeaderNav from '@/components/HeaderNav.vue'
import { getOrderPage, payOrder, cancelOrder } from '@/api/order'
import { getImageUrl, handleImageError as handleImgError } from '@/utils/image'

const router = useRouter()

const loading = ref(false)
const orderList = ref([])
const activeStatus = ref('')
const total = ref(0)
const pagination = ref({
  current: 1,
  size: 20
})

// 加载订单列表
const loadOrderList = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.value.current,
      size: pagination.value.size
    }
    if (activeStatus.value) {
      params.orderStatus = parseInt(activeStatus.value)
    }
    const res = await getOrderPage(params)
    if (res.code === 200) {
      orderList.value = res.data?.records || []
      total.value = res.data?.total || 0
    }
  } catch (error) {
    ElMessage.error('加载订单列表失败')
  } finally {
    loading.value = false
  }
}

// 处理每页大小变化
const handleSizeChange = () => {
  pagination.value.current = 1 // 重置到第一页
  loadOrderList()
}

// 处理页码变化
const handleCurrentChange = () => {
  loadOrderList()
}

// 处理状态变更
const handleStatusChange = () => {
  pagination.value.current = 1 // 切换状态时重置到第一页
  loadOrderList()
}

// 处理支付
const handlePay = async (orderId) => {
  try {
    // 弹出输入支付密码的对话框
    const result = await ElMessageBox.prompt('请输入支付密码', '确认支付', {
      confirmButtonText: '确认支付',
      cancelButtonText: '取消',
      inputType: 'password',
      inputPlaceholder: '请输入支付密码',
      inputValidator: (value) => {
        if (!value) {
          return '支付密码不能为空'
        }
        if (value.length < 6 || value.length > 20) {
          return '支付密码长度必须在6-20位之间'
        }
        return true
      },
      inputErrorMessage: '请输入正确的支付密码'
    })
    
    const paymentPassword = result.value
    const res = await payOrder(orderId, paymentPassword)
    if (res.code === 200) {
      ElMessage.success('支付成功')
      await loadOrderList()
    } else {
      ElMessage.error(res.message || '支付失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('支付失败')
    }
  }
}

// 处理查看物流（跳转到详情页）
const handleViewLogistics = (orderId) => {
  router.push(`/order/${orderId}`)
}

// 处理查看详情
const handleViewDetail = (orderId) => {
  router.push(`/order/${orderId}`)
}

// 处理取消订单
const handleCancel = async (orderId) => {
  try {
    await ElMessageBox.confirm('确定要取消这个订单吗？', '提示', {
      type: 'warning'
    })
    const res = await cancelOrder(orderId)
    if (res.code === 200) {
      ElMessage.success('取消成功')
      await loadOrderList()
    } else {
      ElMessage.error(res.message || '取消失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('取消失败')
    }
  }
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '待支付',
    1: '待发货',
    2: '配送中',
    3: '待取件',
    4: '已完成',
    5: '已取消'
  }
  return statusMap[status] || '未知'
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const typeMap = {
    0: 'danger',    // 待支付 - 红色（需要立即处理）
    1: 'warning',   // 待发货 - 橙色
    2: 'primary',   // 配送中 - 蓝色
    3: 'info',      // 待取件 - 灰色
    4: 'success',   // 已完成 - 绿色
    5: 'info'       // 已取消 - 灰色
  }
  return typeMap[status] || ''
}

// 使用统一的图片错误处理
const handleImageError = handleImgError

// 格式化价格
const formatPrice = (price) => {
  if (!price) return '0.00'
  return Number(price).toFixed(2)
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  return time.replace('T', ' ').substring(0, 19)
}

onMounted(() => {
  loadOrderList()
})
</script>

<style scoped lang="scss">
.order-list-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.breadcrumb {
  margin-bottom: 20px;
}

.filter-tabs {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
}

.order-list {
  .order-card {
    background: white;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    
    .order-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-bottom: 15px;
      border-bottom: 1px solid #eee;
      
      .order-info {
        .order-no {
          font-weight: bold;
          margin-right: 20px;
        }
        
        .order-time {
          color: #999;
          font-size: 14px;
        }
      }
    }
    
    .order-items {
      padding: 15px 0;
      
      .order-item {
        display: flex;
        align-items: center;
        margin-bottom: 15px;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .item-image {
          width: 80px;
          height: 80px;
          margin-right: 15px;
          border-radius: 4px;
          object-fit: cover;
        }
        
        .item-info {
          flex: 1;
          
          .item-name {
            font-size: 16px;
            margin: 0 0 10px 0;
            color: #333;
          }
          
          .item-spec {
            display: flex;
            gap: 20px;
            
            .item-price {
              color: #f56c6c;
              font-weight: bold;
            }
            
            .item-quantity {
              color: #999;
            }
          }
        }
      }
    }
    
    .order-footer {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-top: 15px;
      border-top: 1px solid #eee;
      
      .order-total {
        font-size: 16px;
        
        .total-price {
          font-size: 20px;
          color: #f56c6c;
          font-weight: bold;
          margin-left: 10px;
        }
      }
      
      .order-actions {
        display: flex;
        gap: 10px;
      }
    }
  }
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  background: white;
  padding: 20px;
  border-radius: 8px;
}
</style>
